namespace SubSonic.Sugar
{
    using System;
    using System.IO;

    public static class Files
    {
        public static void CreateToFile(string absolutePath, string fileText)
        {
            using (StreamWriter writer = File.CreateText(absolutePath))
            {
                writer.Write(fileText);
            }
        }

        public static string FromByteCount(long bytes)
        {
            if (bytes > 1073741824M)
            {
                return string.Format("{0:0.00} GB", bytes / 1073741824M);
            }
            if (bytes > 1048576M)
            {
                return string.Format("{0:0.00} MB", bytes / 1048576M);
            }
            if (bytes > 1024M)
            {
                return string.Format("{0:0.00} KB", bytes / 1024M);
            }
            return string.Format("{0} B", bytes);
        }

        public static string GetFileText(string absolutePath)
        {
            using (StreamReader reader = new StreamReader(absolutePath))
            {
                return reader.ReadToEnd();
            }
        }

        public static void UpdateFileText(string absolutePath, string lookFor, string replaceWith)
        {
            string fileText = GetFileText(absolutePath).Replace(lookFor, replaceWith);
            WriteToFile(absolutePath, fileText);
        }

        public static void WriteToFile(string absolutePath, string fileText)
        {
            using (StreamWriter writer = new StreamWriter(absolutePath, false))
            {
                writer.Write(fileText);
            }
        }
    }
}

